package com.good.app.net

import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory

class NetworkManager private constructor() {
    private var mClient: OkHttpClient? = null

    fun init() {
        initOkHttp()
        initRetrofit()
    }

    private fun initRetrofit() {
        retrofit = Retrofit.Builder()
            .client(mClient!!)
            .baseUrl(NetConst.HOST_URL)
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }

    private fun initOkHttp() {
        val logging = HttpLoggingInterceptor()
        logging.setLevel(HttpLoggingInterceptor.Level.BODY)
        mClient = OkHttpClient.Builder()
            .addInterceptor(logging)
            .addInterceptor(TokenInterceptor())
            .build()
    }

    fun <T> create(clazz: Class<T>): T {
        return retrofit!!.create(clazz)
    }

    companion object {
        private var retrofit: Retrofit? = null
        val instance = NetworkManager()
    }
}